package org.grayrabbit.cms.plugin.servlet;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.grayrabbit.cms.plugin.Plugin;
import org.grayrabbit.cms.plugin.elements.ResourceLocation;
import org.grayrabbit.cms.plugin.util.LastModifiedHandler;


/**
 * @author sys53
 * @version 1.0
 * @created 06-一月-2012 17:14:47
 */
public abstract class AbstractDownloadableResource implements DownloadableResource {

	public Plugin plugin;
	public ResourceLocation resourceLocation;
	protected String extraPath;
	protected BaseFileServerServlet servlet;

	public AbstractDownloadableResource(BaseFileServerServlet servlet,Plugin plugin, ResourceLocation resourceLocation,String extraPath) {
		if ((extraPath != null) && (!"".equals(extraPath.trim())) && (!resourceLocation.getLocation().endsWith("/")))
	    {
	      extraPath = "/" + extraPath;
	    }
		this.resourceLocation = resourceLocation;
		this.extraPath = extraPath;
		this.plugin = plugin;
		this.servlet = servlet;
	}


	/**
	 * 
	 * @param response
	 * @param request
	 */
	protected boolean checkResourceNotModified(HttpServletResponse response, HttpServletRequest request){
		Date resourceLastModifiedDate = this.plugin.getDateLoaded() == null ? new Date() : this.plugin.getDateLoaded();
	    LastModifiedHandler lastModifiedHandler = new LastModifiedHandler(resourceLastModifiedDate);
	    return lastModifiedHandler.checkRequest(request, response);
	}

	protected String getContentType(){
		if (this.resourceLocation.getContentType() == null) {
			return this.servlet.getContentType(getLocation());
		}
		return this.resourceLocation.getContentType();
	}

	protected String getLocation(){
		return this.resourceLocation.getLocation() + this.extraPath;
	}

	/**
	 * 
	 * @param response
	 * @param request
	 * @throws IOException 
	 */
	public abstract void serveResource(HttpServletRequest request,HttpServletResponse response) throws IOException;

}